var api = require('./../../config/api.js');
var app = getApp();
var util = require('./../../utils/util.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    expressText: "请选择", // 选择的快递公司
    expressList: ['其它'], // 快递公司下拉框
    expressId: 99,
    expressIdList: [],
    sizeText: "请选择", // 型号内容
    sizeList: ["小", "中", "大"], // 型号下拉框
    showChooseTime: false, // 是否选择定时达
    timeText: "请选择", // 填写的时间
    dateText: "请选择", // 填写的日期
    showConfirm: false,
    takeType:[
      { name: 'common', value: '普通', checked: true },
      { name: 'urgent', value: '加急'},
      { name: 'clock', value: '定时' },
      { name: 'urgentClock', value: '加急定时' },
    ],
    takeValue: "common",
    addressLoad: false, // 是否加载了地址
    takeAddress:{ // 配送地址信息
      takeAddressId: 0,
      takeAddress: "",
      takeSchool: ""
    },
    takeList: [],
    takeIdList: [],
    getAddress: {
      "aaId": 0,
      "uId": "",
      "aaName": "",
      "aaSex": 1,
      "aaMobile": "",
      "csId": 0,
      "csName": "",
      "ssId": 0,
      "ssName": "",
      "aaAddress": "",
      "aaDefault": 0,
      "createTime": ""
    }, // 配送地址信息
    payMoney: 3, // 支付最小金额
    payMin: 3, // 允许最小支付
    payDefault: 3, // 默认支付金额
    smsText: "", // 填写的快递短信
    memoText: "", // 备注
    payInfo: {},
    urgentTimes: 2,
    clockTimes: 1.5,
    ufId: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    console.log(options);
    var tail = '/0'
    if (JSON.stringify(options) != '{}'){
      tail = '/' + options.aaId;
    }

    // 获取价格配置信息
    var configUrl = api.PriceConfig + '/' + app.globalData.userInfo.addition.uCustomInfo.csId + '/express';
    util.myRequest(configUrl, false, function (data) {
      for (var i = 0; i < data.data.length; i++) {
        if (data.data[i].cpProperty == 'common') {
          if (data.data[i].cpPrice > 1){

          }
          that.setData({ payMoney: data.data[i].cpPrice, payMin: data.data[i].cpPrice, payDefault: data.data[i].cpPrice});
        } else if (data.data[i].cpProperty == 'urgentTimes') {
          that.setData({ urgentTimes: data.data[i].cpPrice });
        } else if (data.data[i].cpProperty == 'clockTimes') {
          that.setData({ clockTimes: data.data[i].cpPrice });
        }
      }
    });

    var url = api.CreateOrderInfo + '/' + app.globalData.userInfo.token + tail + '/express';
    util.myRequest(url, false, function(data){
      var info = data.data;

      if (Array.isArray(info.receiveAddressInfo)){
         // 无地址跳转到添加地址
        that.addReceiveAddress();
        return;
      }

      that.setData({
        expressList: info.expressInfo.nameList,
        expressIdList: info.expressInfo.idList,
        sizeList: info.packageSize,
        takeList: info.takeAddressList.nameList,
        takeIdList: info.takeAddressList.idList,
        // takeAddress: info.takeAddressList,
        getAddress: info.receiveAddressInfo,
        addressLoad: true,
      });

      var takeAddress = {};
      var takeList = info.takeAddressList;
      takeAddress.takeAddressId = takeList.idList[0];
      takeAddress.takeAddress = takeList.nameList[0].split(' ')[1];
      takeAddress.takeSchool = takeList.nameList[0].split(' ')[0];

      that.setData({ takeAddress: takeAddress });
      that.getExpress(takeList.idList[0]);
      // 判断本次是否免费
      if (typeof (info.userFree) == 'object' && info.userFree != null){
        that.setData({ufId: info.userFree.ufId});
        that.getDefaultPay();
        wx.showToast({
          title: '此单最低可1毛钱哦',
          icon: 'none',
          duration: 2000
        })
      }
    });

    if (app.globalData.userInfo.isSubscribe == 0) {
      wx.showToast({
        title: '亲，关注校运通公众号，骑士接单后会有微信通知哦!',
        icon: 'none',
        duration: 3000,
        mask: false,
      });
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function (options) {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return app.globalData.shareInfo;
  },

  getExpress: function(stId){
    return;
    var that = this;
    util.myRequest(api.TakeExpress + '/' + stId, false, function(data){
      that.setData({
        expressList: data.data.nameList,
        expressIdList: data.data.idList,
      });
    });
  },

  /**
   * 获取默认金额
   */
  getDefaultPay: function(){
    // 判断是否免费
    if (this.data.ufId != 0) {
      this.setData({
        payMoney: 0.1,
        payMin: 0.1,
      });
      return;
    }

    var that = this;

    if (this.data.getAddress.ssId != 0 && this.data.takeAddress.takeAddressId != 0 && this.data.sizeText != '请选择'){
      var ssId = this.data.getAddress.ssId;
      var stId = this.data.takeAddress.takeAddressId;
      var size = this.data.sizeText;

      var url = api.DefaultPay + '/' + app.globalData.userInfo.addition.uCustomInfo.csId + '/' + stId + '/' + ssId + '/' + size;
      util.myRequest(url, false, function(data){
        // var payMoney = data.data;
        // var payDefault = that.data.payDefault;
        var payDefault = parseFloat(data.data).toFixed(2);
        var coefficient = 1;
        if (that.data.takeValue == 'urgent') {
          coefficient = that.data.urgentTimes;
        } else if (that.data.takeValue == 'clock') {
          coefficient = that.data.clockTimes;
        } else if (that.data.takeValue == 'urgentClock') {
          coefficient = that.data.urgentTimes * that.data.clockTimes
        }

        that.setData({
          payMoney: (payDefault * coefficient).toFixed(2),
          payMin: (payDefault * coefficient).toFixed(2),
        });
        
      });
    }
  },

  /**
   * 选择地址
   */
  expressChange: function (e) {
    var that = this;
    console.log(e.detail)
    console.log('picker发送选择改变，携带值为', e.detail.value)
    that.setData({
      expressText: that.data.expressList[e.detail.value],
      expressId: that.data.expressIdList[e.detail.value],
    })

    this.getDefaultPay();
  },

  /**
   * 关闭地址
   */
  closeExpress: function () {
    var that = this;
    that.setData({ chooseExpress: false });
  },

  /**
   * 选择取货地址列表
   */
  takeListChange: function (e) {
    console.log('radio发生change事件，携带value值为：', e.detail.value)
    var takeAddress = {};
    var takeIdList = this.data.takeIdList;
    var takeList = this.data.takeList;
    takeAddress.takeAddressId = takeIdList[e.detail.value];
    takeAddress.takeAddress = takeList[e.detail.value].split(' ')[1];
    takeAddress.takeSchool = takeList[e.detail.value].split(' ')[0];
    this.setData({ takeAddress: takeAddress});

    this.getDefaultPay();

    this.getExpress(takeIdList[e.detail.value]);
  },

  /**
   * 选择快递大小
   */
  sizeChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    console.log(e)
    this.setData({
      sizeText: this.data.sizeList[e.detail.value]
    })

    this.getDefaultPay();
  },

  /**
   * 选择日期
   */
  dateChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      dateText: e.detail.value
    })
  },

  /**
   * 选择时间
   */
  timeChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      timeText: e.detail.value
    })
  },

  /**
   * 选择送快递时间方式
   */
  takeTypeChange: function (e) {
    console.log('radio发生change事件，携带value值为：', e.detail.value)
    if (e.detail.value == 'urgent'){
      this.setData({ showChooseTime: false});
    } else if (e.detail.value == 'clock'){
      this.setData({ showChooseTime: true });
    } else if (e.detail.value == 'common') {
      this.setData({ showChooseTime: false });
    } else if (e.detail.value == 'urgentClock') {
      this.setData({ showChooseTime: true });
    }
    this.setData({ takeValue: e.detail.value});

    this.getDefaultPay();
  },

  /**
   * 添加取货地址
   */
  addGetAddress: function(){
    console.log('addGetAddress')
    wx.redirectTo({
      url: './../address/list/list?orderType=express'
    })
  },

  /**
   * 添加送达地址
   */
  addReceiveAddress: function(){
    console.log('addReceiveAddress')
    // wx.navigateTo({
    wx.redirectTo({
      url: './../address/list/list?orderType=express'
    })
  },

  /**
   * 跳转收货列表
   */
  goAddressList: function () {
    console.log('goAddressList')
    // wx.navigateTo({
    wx.redirectTo({
      url: './../address/list/list?orderType=express'
    })
  },

  /**
   * 支付金额
   */
  payInput: function (e) {
    var that = this;
    if (e.detail < this.data.payMin){
      this.setData({
        payMoney: that.data.payMoney
      })
    }else{
      this.setData({
        payMoney: e.detail
      })
    }
    
  },

  /**
   * 快递短信
   */
  smsInput: function(e) {
    this.setData({
      smsText: e.detail.value
    })
  },

  /**
   * 订单备注
   */
  memoInput: function (e) {
    this.setData({
      memoText: e.detail.value
    })
  },

  /**
   * 下单
   */
  doOrder: function (e) {
    var that = this;

    if (that.data.expressText == '请选择'){
      wx.showToast({
        title: '请选择快递类型',
        icon: 'none',
        duration: 2000
      })
      return;
    }

    if (that.data.sizeText == '请选择') {
      wx.showToast({
        title: '请选择快递大小',
        icon: 'none',
        duration: 2000
      })
      return;
    }

    if (that.data.smsText == '') {
      wx.showToast({
        title: '请粘贴快递短信',
        icon: 'none',
        duration: 2000
      })
      return;
    }

    var aoServeTime = '';
    if (that.data.takeValue == 'clock' || that.data.takeValue == 'urgentClock'){
      if (that.data.dateText == '请选择'){
        wx.showToast({
          title: '选择配送日期',
          icon: 'none',
          duration: 2000
        })
        return;
      }

      if (that.data.timeText == '请选择'){
        wx.showToast({
          title: '选择配送时间',
          icon: 'none',
          duration: 2000
        })
        return;
      }

      aoServeTime = that.data.dateText + ' ' + that.data.timeText;
    }

    var postData = {
      token: app.globalData.userInfo.token,
      aaId: that.data.getAddress.aaId,
      stId: that.data.takeAddress.takeAddressId,
      csId: that.data.getAddress.csId,
      ceId: that.data.expressId,
      ceName: that.data.expressText,
      aoExpressWeight: that.data.sizeText,
      aoLevel: that.data.takeValue,
      aoServeTime: aoServeTime,
      aoPay: that.data.payMoney,
      aoSmsCopy: that.data.smsText,
      aoMemo: that.data.memoText,
      ufId: that.data.ufId,
    };

    util.myRequest(api.AddOrder, postData, function(data){
      that.setData({ payInfo: data.data });
      that.wxPay();
    });
  },

  wxPay: function(){
    var that = this;
    var showDuration = 2000;
    wx.requestPayment({
      'timeStamp': that.data.payInfo.timeStamp,
      'nonceStr': that.data.payInfo.nonceStr,
      'package': that.data.payInfo.package,
      'signType': 'MD5',
      'paySign': that.data.payInfo.paySign,
      'success': function (res) {
        wx.showToast({
          title: '支付成功',
          icon: 'success',
          duration: showDuration
        })

        setTimeout(function () {

          wx.redirectTo({
            url: './../order/order'
          })
          // wx.navigateBack({
          //   delta: 1
          // })
        }, showDuration);
      },
      'fail': function (res) {
        wx.showToast({
          title: '支付失败',
          icon: 'success',
          duration: showDuration
        })
        
        setTimeout(function () {

          wx.redirectTo({
            url: './../order/order'
          })
          // wx.navigateBack({
          //   delta: 1
          // })
        }, showDuration);
      }
    })
  }
})